package cn.q3c.web.tool;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.keyvalue.ccf.common.http.NewRequestUtils;
import cn.q3c.web.tool.dao.UrlDAO;
import cn.q3c.web.tool.object.Url;

@Controller
public class RedirectWebService {

	@Autowired
	@Qualifier("urlDAO")
	private UrlDAO urlDAO = null;
	
	/**
	 * 跳转入口，参数为url，返回是spring中的redirect语法
	 * 
	 * 对于cps链接，可以动态修改返回
	 * 所以以后这里会有其他逻辑加入
	 * 
	 * @param request
	 * @return
	 * @throws SQLException 
	 * @throws IOException 
	 * @throws HttpException 
	 */
	@RequestMapping("/redirect.do")
	public String processRedirect( HttpServletRequest request, @RequestParam("target") String targetUrl ) throws SQLException, HttpException, IOException
	{		
		Url url = urlDAO.getUrl(targetUrl);
		
		if( url == null )
		{
			url = new Url();
			url.setUrl(targetUrl);
			String trueUrl = NewRequestUtils.getTrueURL(targetUrl);
			url.setTrueurl(trueUrl);
			urlDAO.addUrl(url);
		}
		else
		{
			urlDAO.updateUrlDate(url.getNid());
			
		}		
		
		String retUrl = url.getTrueurl();		
		return "redirect:" + retUrl;
	}
}
